package cn.zjh.basic.inInterceptor;

import cn.zjh.basic.annotation.PreAuthorize;
import cn.zjh.basic.jwt.JwtUtils;
import cn.zjh.basic.jwt.LoginData;
import cn.zjh.basic.jwt.Payload;
import cn.zjh.basic.jwt.RsaUtils;
import cn.zjh.user.domain.Logininfo;
import cn.zjh.user.mapper.LogininfoMapper;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        //如果有token，就通过token获取redis的信息
        if (token!= null){
            //获得公钥
            PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
            try {
                //使用公钥解析JWTtoken,获得想要的数据，LoginData
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                if (payload != null){//登录成功.并且登录信息没有过期
                    //获取登录信息:logininfo
                    Logininfo logininfo = payload.getLoginData().getLogininfo();
                    //如果是用户就放行
                    if (logininfo.getType() == 1){
                        return true;
                    }
                    //获取当前接口上注解里的sn
                    HandlerMethod handlerMethod = (HandlerMethod) handler;//接受请求的方法，接口
                    //获得所有含有PreAuthorize注解的接口
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);

                    if (preAuthorize == null){   //接口上没有preAuthorize注解就直接放行，属于公共资源，不需要权限校验
                        return true;
                    }else {
                        String sn = preAuthorize.sn();//获得所有的权限
                        //根据logininfoid获得登录人的所有权限
                        List<String> sns = logininfoMapper.loadPermissionsByLogininfoId(logininfo.getId());

                        if (sns.contains(sn)){//如果有权限就放行
                            return true;
                        }else {
                            response.setContentType("application/json;charset=UTF-8");
                            response.getWriter().println("{\"success\":false,\"message\":\"noPermission\"}");

                            return false;
                        }
                    }
                }
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"message\":\"timeout\"}");
                return false;
            }
        }
        //跳转到登录页面，在前端跳转
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}");
        return false;
    }
}
